package com.windrift.springhibernate.service;

import com.windrift.springhibernate.service.CostTypeService;
import com.windrift.springhibernate.model.CostType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

@Transactional
@Service("costTypeService")
public class CostTypeServiceImpl implements CostTypeService {
    private EntityManager em;

    @PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    @SuppressWarnings("unchecked")
    public List<CostType> findAll() {
        Query query = getEntityManager().createQuery("SELECT c FROM CostType c WHERE c.parent IS NULL ORDER BY sequence ASC, id DESC");
        return query.getResultList();
    }

    public List<CostType> findChildren(Integer parentId) {

       Query query = getEntityManager().createQuery("SELECT c FROM CostType c WHERE c.parent = " + parentId + " ORDER BY sequence ASC, id DESC");
       List<CostType> items= query.getResultList();

       return items;
   }


    private void save(CostType costType) {
        if (costType.getId() == null) {
            // new
            em.persist(costType);
        } else {
            // update
            em.merge(costType);
        }
    }

    public void remove(int id) {
        CostType costType = find(id);
        if (costType != null) {
            em.remove(costType);
        }
    }

    private EntityManager getEntityManager() {
        return em;
    }

    public CostType find(int id) {
        return em.find(CostType.class, id);
    }

    public void add(CostType costType) {
        this.save(costType);        
    }

    public void update(CostType costType) {
        this.save(costType);        
    }

}
